import { defineStore } from "pinia";
import { computed, type Ref, ref } from "vue";
import type { AddressDTO, AddressVO } from "@/types/addressType";
import { addAddressAPI, deleteAddressAPI, fetchAddressListAPI, findAddressDetailAPI, updateAddressAPI } from "@/api/addressAPI";
import Address from "@/subPackages/address/address.vue";

const useAddressStore = defineStore("addressStore", () => {
   // 收货地址列表
   const addressList: Ref<AddressVO[]> = ref<AddressVO[]>([]);

   const defaultAddress = computed({
      get() {
         return addressList.value.find(item => item.isDefault === 1) || addressList.value[0];
      },
      set(newValue) {
         const currentAddress = addressList.value.find(item => item.id === newValue.id) as AddressVO;
         addressList.value.forEach(item=>item.isDefault=0)
         currentAddress.isDefault=1
      },

   });
   // 发送请求获取收货地址的回调函数
   const fetchAddressList = async (): Promise<void> => {
      try {
         const { result }: { result: AddressVO[] } = await fetchAddressListAPI();
         addressList.value = result;
      } catch (error: any) {
         await error;
      }
   };

   // 发送请求添加收货地址的回调函数
   const addAddress = async (data: AddressDTO): Promise<void> => {
      try {
         await addAddressAPI(data);
      } catch (error: any) {
         await error;
      }
   };
   // 发送删除收货地址的回调函数
   const deleteAddress = async (id: string) => {
      try {
         await deleteAddressAPI(id);
      } catch (error: any) {
         await error;
      }
   };
   // 获取收货地址详情的回调函数
   const findAddressDetail = async (id: string) => {
      try {
         const { result }: { result: AddressVO } = await findAddressDetailAPI(id);
         return result;
      } catch (error: any) {
         await error;
      }
   };
   // 发送请求修改收货地址的回调函数
   const updateAddress = async (id: string, data: AddressDTO) => {
      try {
         await updateAddressAPI(id, data);
      } catch (error: any) {
         await error;
      }
   };
   return {
      addressList,
      defaultAddress,
      fetchAddressList,
      addAddress,
      deleteAddress,
      findAddressDetail,
      updateAddress,
   };
});

export default useAddressStore;